package gptma.fo.controler;

import gptma.bo.model.project.Project;
import gptma.bo.services.project.ProjectServices;
import java.io.Serializable;

import java.text.DateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.ejb.EJB;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;

@Named("app")
@ApplicationScoped
public class Application implements Serializable {

	private static final long serialVersionUID = -2419357794322876541L;

	public static final String NAME = "app";
	public static final String MSG_BDL = "messages";
	private static final String CONF_BDL = "gptma";

	private List<Project> allProjects;

	private static final Comparator<Project> PROJECT_COMP = new Comparator<Project>() {

		@Override
		public int compare(Project o1, Project o2) {
			return o1.getName().compareTo(o2.getName());
		}

	};

	@EJB
	private ProjectServices projectServices;

	private String dateFormat;
	private int imputationRemovalDayLimit;

	public Application() {
		ResourceBundle bdl = ResourceBundle.getBundle(CONF_BDL);
		dateFormat = bdl.getString("dateFormat");
		imputationRemovalDayLimit = Integer.valueOf(bdl
				.getString("deletingTimeLimit"));
	}

	public String getDate() {
		Locale loc = FacesContext.getCurrentInstance().getViewRoot()
				.getLocale();
		DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL,
				DateFormat.SHORT, loc);
		return df.format(new Date());
	}

	/**
	 * @return the allProjects
	 */
	public List<Project> getAllProjects() {
		if (allProjects == null) {
			allProjects = projectServices.findAll();
		}

		return allProjects;
	}

	public Project getProject(String projectName) {
		Project ret = null;
		List<Project> list = getAllProjects();

		Collections.sort(list, PROJECT_COMP);
		Project key = new Project();
		key.setName(projectName);
		int found = Collections.binarySearch(list, key, PROJECT_COMP);

		if (found > -1) {
			ret = list.get(found);
		}

		return ret;
	}

	public String getRoot() {
		return FacesContext.getCurrentInstance().getExternalContext()
				.getRequestContextPath();
	}

	/**
	 * @return the dateFormat
	 */
	public String getDateFormat() {
		return dateFormat;
	}

	public int getImputationRemovalDayLimit() {
		return imputationRemovalDayLimit;
	}

}
